package org.dromara.merchants.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.merchants.domain.TaAssociation;
import org.dromara.merchants.mapper.TaAssociationMapper;
import org.springframework.stereotype.Service;
import org.dromara.merchants.domain.bo.TaSetMealBo;
import org.dromara.merchants.domain.vo.TaSetMealVo;
import org.dromara.merchants.domain.TaSetMeal;
import org.dromara.merchants.mapper.TaSetMealMapper;
import org.dromara.merchants.service.ITaSetMealService;

import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 套餐Service业务层处理
 *
 * @author xiyin321
 * @date 2024-07-07
 */
@RequiredArgsConstructor
@Service
public class TaSetMealServiceImpl implements ITaSetMealService {

    private final TaSetMealMapper baseMapper;
    private final TaAssociationMapper associationMapper;

    /**
     * 查询套餐
     */
    @Override
    public TaSetMealVo queryById(Long setMealId) {
        TaSetMealVo vo = baseMapper.selectVoById(setMealId);
        vo.setAssociationList(associationMapper.selectAssociationListById(vo.getSetMealId(), "1"));
        return vo;
    }

    /**
     * 查询套餐列表
     */
    @Override
    public TableDataInfo<TaSetMealVo> queryPageList(TaSetMealBo bo, PageQuery pageQuery) {
        Page<TaSetMealVo> result = baseMapper.selectSetMealPage(pageQuery.build(), this.buildQueryWrapper(bo));
        result.getRecords().forEach(item -> {
            item.setAssociationList(associationMapper.selectAssociationListById(item.getSetMealId(), "1"));
        });
        return TableDataInfo.build(result);
    }

    /**
     * app端查询套餐列表
     *
     * @param bo
     * @param pageQuery
     */
    @Override
    public TableDataInfo<TaSetMealVo> queryAppList(TaSetMealBo bo, PageQuery pageQuery) {
        bo.setStatus("0");
        Page<TaSetMealVo> result = baseMapper.selectAppPage(pageQuery.build(), this.buildQueryWrapper(bo));
        return TableDataInfo.build(result);
    }

    /**
     * 查询套餐列表
     */
    @Override
    public List<TaSetMealVo> queryList(TaSetMealBo bo) {
        return baseMapper.selectVoList(this.buildQueryWrapper(bo));
    }

    /*构建查询条件*/
    private Wrapper<TaSetMeal> buildQueryWrapper(TaSetMealBo bo) {
        QueryWrapper<TaSetMeal> wrapper = Wrappers.query();
        wrapper.eq("sm.del_flag", "0")
            .eq(StringUtils.isNotBlank(bo.getSetMealName()), "sm.set_meal_name", bo.getSetMealName())
            .eq(ObjectUtil.isNotNull(bo.getStoreId()), "sm.store_id", bo.getStoreId())
            .eq(ObjectUtil.isNotNull(bo.getClassificationId()), "sm.classification_id", bo.getClassificationId())
            .eq(ObjectUtil.isNotNull(bo.getCategoryId()), "sm.category_id", bo.getCategoryId())
            .eq(ObjectUtil.isNotEmpty(bo.getStatus()), "sm.status", bo.getStatus());
        return wrapper;
    }

    private LambdaQueryWrapper<TaSetMeal> buildLambdaQueryWrapper(TaSetMealBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<TaSetMeal> lqw = Wrappers.lambdaQuery();
        lqw.
            like(StringUtils.isNotBlank(bo.getSetMealName()), TaSetMeal::getSetMealName, bo.getSetMealName())
            .eq(ObjectUtil.isNotNull(bo.getStoreId()), TaSetMeal::getStoreId, bo.getStoreId())
            .eq(ObjectUtil.isNotNull(bo.getClassificationId()), TaSetMeal::getClassificationId, bo.getClassificationId())
            .eq(ObjectUtil.isNotNull(bo.getCategoryId()), TaSetMeal::getCategoryId, bo.getCategoryId())
            .eq(TaSetMeal::getStatus, '0');
        return lqw;
    }

    /**
     * 新增套餐
     */
    @Override
    public Boolean insertByBo(TaSetMealBo bo) {
        List<TaAssociation> associations = MapstructUtils.convert(bo.getAssociationList(), TaAssociation.class);
        TaSetMeal add = MapstructUtils.convert(bo, TaSetMeal.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (associations != null && !associations.isEmpty()) {
            associations.forEach(item -> {
                item.setParentId(add.getSetMealId());
            });
        }
        /*插入套餐商品关联*/
        associationMapper.insertBatch(associations);
        if (flag) {
            bo.setSetMealId(add.getSetMealId());
        }
        return flag;
    }

    /**
     * 修改套餐
     */
    @Override
    public Boolean updateByBo(TaSetMealBo bo) {
        List<TaAssociation> associations = MapstructUtils.convert(bo.getAssociationList(), TaAssociation.class);
        TaSetMeal update = MapstructUtils.convert(bo, TaSetMeal.class);
        validEntityBeforeSave(update);
        boolean flag = baseMapper.updateById(update) > 0;
        if (associations != null && !associations.isEmpty()) {
            associations.forEach(item -> {
                item.setParentId(update.getSetMealId());
            });
        }
        /*插入数据前先将旧数据删除*/
        associationMapper.delete(new LambdaQueryWrapper<TaAssociation>().eq(TaAssociation::getParentId, update.getSetMealId()));
        /*插入套餐商品关联*/
        associationMapper.insertBatch(associations);
        return flag;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(TaSetMeal entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除套餐
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            /*在删除商品时，将关联表的相关记录删除*/
            associationMapper.delete(new LambdaQueryWrapper<TaAssociation>().in(TaAssociation::getParentId, ids));
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
